﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using Zero.UControl.Base.Helper.Base.UAdorner;

namespace Zero.UControl.Base.Helper.Base
{
    internal class UngroupCommand : IDrawingCommand
    {

        private readonly Canvas _c;
        private readonly Canvas _g;
        private readonly SelectionService _s;
        private readonly List<UIElement> _items = new();
        private double _gx, _gy;

        public UngroupCommand(Canvas canvas, Canvas group, SelectionService svc)
        {
            _c = canvas;
            _g = group;
            _s = svc;
        }

        public void Execute()
        {
            _gx = Canvas.GetLeft(_g);
            _gy = Canvas.GetTop(_g);
            foreach (UIElement el in _g.Children)
                _items.Add(el);
            foreach (var el in _items)
            {
                _g.Children.Remove(el);
                _c.Children.Add(el);
                Canvas.SetLeft(el, _gx + Canvas.GetLeft(el));
                Canvas.SetTop(el, _gy + Canvas.GetTop(el));
                _s.Attach(el);
            }
            _c.Children.Remove(_g);
        }
        public void UnExecute()
        {
            _c.Children.Add(_g);
            Canvas.SetLeft(_g, _gx);
            Canvas.SetTop(_g, _gy);
            foreach (var el in _items)
            {
                _c.Children.Remove(el);
                _g.Children.Add(el);
                Canvas.SetLeft(el, Canvas.GetLeft(el) - _gx);
                Canvas.SetTop(el, Canvas.GetTop(el) - _gy);
                _s.Detach(el);
            }
        }
    }
}
